package com.hy.generator.common.api;


import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.With;
import org.springframework.util.ObjectUtils;

import java.io.Serial;
import java.io.Serializable;

@Getter
@ToString
@RequiredArgsConstructor(onConstructor_ = {@JsonCreator})
public class ApiResult<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    private static final ApiResult<Boolean> SUCCESS = new ApiResult<>(
            ApiResult.SUCCESS_CODE, ApiResult.SUCCESS_MSG, true);

    private static final ApiResult<Void> OK = new ApiResult<>(
            ApiResult.SUCCESS_CODE, ApiResult.SUCCESS_MSG, null);

    private static final ApiResult<Void> FAILED = new ApiResult<>(
            ApiResult.BUSINESS_FAIL_CODE, ApiResult.FAIL_MSG, null);

    public static final int SUCCESS_CODE = 200;
    public static final int INTERNAL_FAIL_CODE = 500;
    public static final int BUSINESS_FAIL_CODE = 800;
    public static final int UNAUTHORIZED_CODE = 401;

    public static final String SUCCESS_MSG = "success";
    public static final String FAIL_MSG = "fail";

    /**
     * 返回状态码；200:成功"
     */
    private final int code;

    /**
     * 成功标识；success：成功；fail:失败"
     */
    @With
    private final String msg;

    /**
     * 返回内容
     */
    private final T content;

    @JsonIgnore
    public boolean isSuccess() {
        return code == SUCCESS_CODE;
    }

    @JsonIgnore
    public boolean isEmpty() {
        return ObjectUtils.isEmpty(content);
    }

    public static ApiResult<Void> ok() {
        return OK;
    }

    public static ApiResult<Boolean> success() {
        return SUCCESS;
    }

    public static <T> ApiResult<T> success(T content) {
        return new ApiResult<>(ApiResult.SUCCESS_CODE, ApiResult.SUCCESS_MSG, content);
    }

    public static ApiResult<Void> fail() {
        return FAILED;
    }

    public static <T> ApiResult<T> fail(String msg) {
        return new ApiResult<>(ApiResult.BUSINESS_FAIL_CODE, msg, null);
    }

    public static <T> ApiResult<T> fail(int code, String msg) {
        return new ApiResult<>(code, msg, null);
    }

    public static <T> ApiResult<T> fail(T content) {
        return fail(content, null);
    }

    public static <T> ApiResult<T> fail(T content, String msg) {
        return new ApiResult<>(ApiResult.BUSINESS_FAIL_CODE, msg, content);
    }

    public static <T> ApiResult<T> unAuth() {
        return new ApiResult<>(UNAUTHORIZED_CODE, "token无效或已过期", null);
    }
    
}
